package com.yunkeji.api.help.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunkeji.api.help.bo.HelpListBo;
import com.yunkeji.api.help.service.HelpService;
import com.yunkeji.api.help.vo.LimitList;
import com.yunkeji.common.core.page.TableDataInfo;
import com.yunkeji.dao.domain.UserBanned;
import com.yunkeji.dao.domain.sys.SysHelp;
import com.yunkeji.dao.mapper.SysHelpMapper;
import com.yunkeji.dao.mapper.UserBannedMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@AllArgsConstructor
public class HelpServiceImpl implements HelpService {

    private final UserBannedMapper userBannedMapper;
    private final SysHelpMapper sysHelpMapper;

    @Override
    public List<LimitList> bannerList() {
        List<UserBanned> userBanneds =
                userBannedMapper.selectList(
                        Wrappers.lambdaQuery(UserBanned.class)
                                .orderBy(true, false, UserBanned::getCreateTime)
                                .last("limit 20 "));

        List<LimitList> limitLists =
                BeanUtil.copyToList(
                        userBanneds,
                        LimitList.class,
                        CopyOptions.create()
                                .setConverter(
                                        (type, value) -> {
                                            if (type.getTypeName().equalsIgnoreCase("Long"))
                                                return String.valueOf(value);
                                            return value;
                                        }));
        limitLists.forEach(item -> item.setReason(item.getReason() + (!Objects.isNull(item.getLimitType()) && item.getLimitType().equals(99) ? "-永久封禁" : "")));

        return limitLists;
    }

    @Override
    public TableDataInfo<SysHelp> helpList(HelpListBo bo) {
        Page<SysHelp> sysHelpPage =
                sysHelpMapper.selectPage(bo.build(), Wrappers.lambdaQuery(SysHelp.class));
        return TableDataInfo.build(sysHelpPage);
    }

    @Override
    public Long bannerCount() {
        return userBannedMapper.selectCount(
                Wrappers.lambdaQuery(UserBanned.class)
                        .gt(UserBanned::getCreateTime, DateUtil.beginOfYear(new Date())));
    }
}
